<template>
  <div id="viewerContainer"></div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import { useCesium } from "../composables";

const { initViewer } = useCesium("viewerContainer");
import * as Cesium from "cesium";

onMounted(() => {
  const viewer = initViewer();

  viewer.scene.globe.depthTestAgainstTerrain = true;

  const primitives = viewer.scene.primitives;

  // 定义视锥的原点（位置）
  const origin = Cesium.Cartesian3.fromDegrees(110.59777, 40.03883, 10000.0);

  // 定义视锥的方向（姿态）
  const orientation = Cesium.Transforms.headingPitchRollQuaternion(
    origin,
    new Cesium.HeadingPitchRoll(
      Cesium.Math.toRadians(30), // 航向角：45度
      Cesium.Math.toRadians(-180), // 俯仰角：向下倾斜30度
      Cesium.Math.toRadians(-30) // 翻滚角：无侧倾
    )
  );

  const horizontalFov = Cesium.Math.toRadians(60); // 水平张角 60 度
  const verticalFov = Cesium.Math.toRadians(45); // 垂直张角 45 度

  // 计算宽高比
  const aspectRatio = Math.tan(horizontalFov / 2) / Math.tan(verticalFov / 2);

  const geometry = new Cesium.FrustumGeometry({
    frustum: new Cesium.PerspectiveFrustum({
      fov: verticalFov, // 视场角
      aspectRatio, // 宽高比
      near: 0.001, // 近裁剪面
      far: 100000.0, // 远裁剪面
    }),
    origin, // 视锥原点
    orientation, // 视锥方向
  });

  // 使用 FrustumGeometry 创建填充的视锥
  const primitive = new Cesium.Primitive({
    geometryInstances: new Cesium.GeometryInstance({
      geometry,
    }),
    appearance: new Cesium.MaterialAppearance({
      material: Cesium.Material.fromType("Color", {
        color: Cesium.Color.YELLOW.withAlpha(0.5), // 设置颜色和透明度
      }),
    }),
  });

  //   primitives.add(primitive);

  primitives.add(
    new Cesium.ClassificationPrimitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry,
        attributes: {
          // 直接通过颜色属性覆盖
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(
            Cesium.Color.RED.withAlpha(0.8)
          ),
        },
      }),
      classificationType: Cesium.ClassificationType.TERRAIN,
      appearance: new Cesium.Appearance({
        material: new Cesium.Material({
          fabric: {
            type: "Color",
            uniforms: {
              color: new Cesium.Color(1.0, 1.0, 0.0, 1.0),
            },
          },
        }),
      }),
    })
  );

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(110.59777, 40.03883, 50000),
    duration: 0,
  });
});
</script>

<style scoped lang="less">
#viewerContainer {
  height: 100vh;
}
</style>
